<route lang="json5" type="page">
{
style: {
navigationBarTitleText: '班级',
},
}
</route>

<script setup lang="ts">
import api from '@/api'
import AssignmentSection from '@/components/class/AssignmentSection.vue'
import MemberSection from '@/components/class/MemberSection.vue'
import NotJoined from '@/components/class/NotJoined.vue'
import PanelSection from '@/components/class/PanelSection.vue'
import TabSection from '@/components/class/TabSection.vue'
import { useClassStore } from '@/store'

const classStore = useClassStore()

interface DataType {
  status: 'Loading' | 'Error' | 'Success'
  currentTag: '作业' | '打卡' | '成员'
  classIndex: number
  classInfos: any[]
  punchStats: {
    todayPunchedCount: number
    totalMembers: number
  }
}
const data = reactive<DataType>({
  status: 'Loading',
  currentTag: '作业',
  classIndex: -1,
  classInfos: [],
  punchStats: {
    todayPunchedCount: 0,
    totalMembers: 0
  }
})

async function fetchData() {
  data.status = 'Loading'

  try {
    const { data: classList } = await api.classes.getClassesByCurrentUser()
    data.classInfos = await Promise.all(classList.map(async (cls) => {
      const { data: info } = await api.classes.getClassInfoByClassId(cls.id)
      return { ...cls, ...info }
    }))

    if (data.classInfos.length > 0) {
      if (classStore.initialClassId !== null) {
        const initialClassIndex = data.classInfos.findIndex(({ id }) => id === classStore.initialClassId)
        data.classIndex = initialClassIndex > -1 ? initialClassIndex : 0
        classStore.clearInitialClassId()
      }
      else {
        data.classIndex = 0
      }
    }
    else {
      data.classIndex = -1
    }

    data.status = 'Success'
    // 加载打卡统计数据
    await loadPunchStats()
  }
  catch (e) {
    data.status = 'Error'
  }
}

onLoad(fetchData)

onShow(() => {
  if (classStore.refresh) {
    fetchData().then(() => {
      classStore.setRefresh(false)
    })
  }
})

function onClassChange(classIndex: number) {
  data.classIndex = classIndex
  // 切换班级时重新加载打卡统计
  loadPunchStats()
}

function onTagChange(tag: DataType['currentTag']) {
  data.currentTag = tag
}

// 获取今日打卡人数
const getTodayPunchedCount = (punchRecords: any[]): number => {
  const today = new Date()
  const todayStr = today.toISOString().split('T')[0] // YYYY-MM-DD格式

  return punchRecords.filter(record => {
    const recordDate = record.punchDate
    if (Array.isArray(recordDate)) {
      // 如果是数组格式 [year, month, day]
      const recordDateStr = `${recordDate[0]}-${recordDate[1].toString().padStart(2, '0')}-${recordDate[2].toString().padStart(2, '0')}`
      return recordDateStr === todayStr
    } else if (typeof recordDate === 'string') {
      // 如果是字符串格式
      return recordDate.startsWith(todayStr)
    }
    return false
  }).length
}

// 加载打卡统计数据
async function loadPunchStats() {
  if (data.classIndex === -1) return

  const classId = data.classInfos[data.classIndex].id
  try {
    const [punchResp, studentsResp] = await Promise.all([
      api.classes.getPunchRecordsByClassId(classId),
      api.classes.getStudentsByClassId(classId) // 只获取学生，用于打卡统计
    ])

    if (punchResp.code === 0 && studentsResp.code === 0) {
      data.punchStats = {
        todayPunchedCount: getTodayPunchedCount(punchResp.data),
        totalMembers: studentsResp.data.length // 只统计学生数量
      }
    }
  } catch (error) {
    console.error('获取打卡统计失败:', error)
  }
}
</script>

<template>
  <view v-if="data.status === `Loading`" style="text-align: center;" class="class-container">
    <wd-loading />
  </view>
  <view v-else-if="data.status === `Error`" style="text-align: center;" class="class-container">
    <text>网络错误！</text>
  </view>
  <view v-else-if="data.classIndex > -1" class="class-container">
    <PanelSection :class-infos="data.classInfos" :class-index="data.classIndex" :on-class-change="onClassChange" />

    <TabSection :tags="['作业', '打卡', '成员']" :current-tag="data.currentTag" :on-tag-change="onTagChange" :punch-stats="data.punchStats" />

    <AssignmentSection v-if="data.currentTag === '作业'" :class-info="data.classInfos[data.classIndex]" />

    <PunchSection v-else-if="data.currentTag === `打卡`" :class-info="data.classInfos[data.classIndex]" />

    <MemberSection v-else-if="data.currentTag === `成员`" :class-info="data.classInfos[data.classIndex]" />
  </view>
  <view v-else class="class-container">
    <NotJoined />
  </view>
</template>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

@mixin section($margin-bottom: $section-margin) {
  padding: $container-padding;
  border-radius: $border-radius-xl;
  background-color: $white;
  box-shadow: $shadow-lg;
  margin-bottom: $margin-bottom;
}

.class-container {
  padding: 15px;
  background: linear-gradient(135deg, #e0f6ff 0%, #f0fff0 50%, #fff5ee 100%);
  min-height: 100vh;
}
</style>
